package com.unytech.project.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PropertiesUtils {
	private static Log logger = LogFactory.getLog(PropertiesUtils.class);
	
	public static Properties loadProperties(String filepath) throws IOException {
		Properties proper = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream(filepath);
			proper.load(input);
		} catch (Exception e) {
			logger.info(e.getMessage());
			logger.error(e, e);
		} finally {
			if (input != null)
				input.close();
		}
	    return proper;
	}

	public static void persisterProperties(Properties proper, String filepath) throws IOException {
		OutputStream out = null;
		try {
			File file = new File(filepath);
			if (!file.exists())
				file.createNewFile();
			out = new FileOutputStream(file);
			proper.store(out, "DolphinBoy");
		} catch (Exception e) {
			logger.info(e.getMessage());
			logger.error(e, e);
		} finally {
			if (out != null)
				out.close(); 
		}
	}
	
	public static void updateProperties(Properties newproper, String filepath) throws IOException {
		Properties proper = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream(filepath);
			proper.load(input);
		} catch (Exception e) {
			logger.info(e.getMessage());
			logger.error(e, e);
		} finally {
			if (input != null)
				input.close();
		}
		
		proper.putAll(newproper);
		
		OutputStream out = null;
		try {
			File file = new File(filepath);
			if (!file.exists())
				file.createNewFile();
			out = new FileOutputStream(file);
			proper.store(out, "DolphinBoy");
		} catch (Exception e) {
			logger.info(e.getMessage());
			logger.error(e, e);
		} finally {
			if (out != null)
				out.close(); 
		}
	}
	
	public static void main (String[] args) throws IOException {
		Properties proper = new Properties();
		proper.setProperty("cc", "bbb");
		PropertiesUtils.persisterProperties(proper, "D:\\jdbc.properties");
	}
	
}
